package com.gist.cithub.evaluate.utils;

import java.io.*;

/**
 * 文件读写工具
 */
public class IOUtil {
    /**
     * 读取文件所有内容
     * @param filepath 文件路径
     * @return 文件内容字符串
     */
    public static String readToString(String filepath) {
        StringBuffer sdf = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new FileReader(filepath));
            String line = null;
            while ((line = br.readLine()) != null) {
                sdf.append(line+"\n\r");
            }
            br.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
        return sdf.toString();
    }
    public static boolean isFile(String path){
        File file=new File(path);
        return file.exists();
    }
    /**
     * 写入文件
     * @param filepath 文件路径
     * @param fileContent 写入内容
     * @param flag 是否覆盖
     */
    public static void writeMethod(String filepath,String fileContent,Boolean flag){
        try{
            BufferedWriter out=new BufferedWriter(new FileWriter(filepath,flag));
            out.write(fileContent);
            out.close();
        } catch (IOException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 清空某个文件夹
     * @param path
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }
    //删除文件夹
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
